import { useIntl } from '@umijs/max';
import { ConfigProvider } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import './EventInfo.less';

export interface IEvent {
  eventKey?: number;
  eventTime?: string;
  eventStatus?: string;
  eventPloy: string | null | undefined;
  eventGrade?: string;
  eventDes?: string;
  eventID?: string;
}

export interface EventInfoProps {
  eventType?: string;
  eventData: IEvent[];
  isScrolling?: boolean;
  columnWidths?: string[]; // 新增属性
}

export interface EventInfoRef {
  pauseScrolling: () => void;
  resumeScrolling: () => void;
}

const EventInfo = forwardRef<EventInfoRef, EventInfoProps>(
  ({ eventType, eventData, isScrolling = false, columnWidths = [] }, ref) => {
    const [scrolling, setScrolling] = useState(isScrolling);
    const [scrollTop, setScrollTop] = useState(0);
    const warperRef = useRef<HTMLDivElement>(null);
    const contentWrapperRef = useRef<HTMLDivElement>(null);
    const childDom1Ref = useRef<HTMLDivElement>(null);
    const childDom2Ref = useRef<HTMLDivElement>(null);
    const speed = 30;
    const intl = useIntl();

    useEffect(() => {
      setScrolling(isScrolling);
    }, [isScrolling]);

    useEffect(() => {
      let timer: NodeJS.Timeout;

      if (scrolling && warperRef.current && childDom1Ref.current && childDom2Ref.current) {
        childDom2Ref.current.innerHTML = childDom1Ref.current.innerHTML;

        timer = setInterval(() => {
          if (warperRef.current && childDom1Ref.current) {
            if (warperRef.current.scrollTop >= childDom1Ref.current.scrollHeight) {
              warperRef.current.scrollTop = 0;
            } else {
              warperRef.current.scrollTop++;
            }
          }
        }, speed);
      }

      return () => {
        clearInterval(timer);
      };
    }, [scrolling, eventData.length]);

    const hoverHandler = (flag: boolean) => {
      if (isScrolling) {
        setScrolling(flag);
      }
    };

    useImperativeHandle(ref, () => ({
      pauseScrolling: () => {
        if (warperRef.current) {
          setScrolling(false);
          setScrollTop(warperRef.current.scrollTop);
        }
      },
      resumeScrolling: () => {
        if (warperRef.current) {
          warperRef.current.scrollTop = scrollTop;
          setScrolling(true);
        }
      },
    }));

    const getHeaders = () => {
      let headers = [
        intl.formatMessage({ id: 'global.s/N' }),
        intl.formatMessage({ id: 'global.time' }),
        intl.formatMessage({ id: 'global.status' }),
        intl.formatMessage({ id: 'global.policyExecutionEvents' }),
      ];

      if (eventType === 'warning') {
        headers = [
          intl.formatMessage({ id: 'global.s/N' }),
          intl.formatMessage({ id: 'global.grade' }),
          intl.formatMessage({ id: 'global.eventDescription' }),
          intl.formatMessage({ id: 'global.locationID' }),
        ];
      }

      return headers;
    };

    const headerElements = getHeaders().map((header, index) => (
      <div
        key={index}
        className={`event-info-header-cell`}
        style={{ flex: columnWidths[index] ? `0 0 ${columnWidths[index]}` : '1 1 0' }}
      >
        {header}
      </div>
    ));

    const rowElements = eventData.map((event, index) => (
      <div key={event.eventKey || index} className="event-info-row">
        <div
          className="event-info-cell"
          style={{ flex: columnWidths[0] ? `0 0 ${columnWidths[0]}` : '1 1 0' }}
        >
          {event.eventKey}
        </div>
        <div
          className="event-info-cell"
          style={{ flex: columnWidths[1] ? `0 0 ${columnWidths[1]}` : '1 1 0' }}
        >
          {eventType === 'warning' ? event.eventGrade : event.eventTime}
        </div>
        <div
          className="event-info-cell"
          style={{ flex: columnWidths[2] ? `0 0 ${columnWidths[2]}` : '1 1 0' }}
        >
          <span className="truncate-text">{event.eventStatus}</span>
        </div>
        <div
          className="event-info-cell"
          style={{ flex: columnWidths[3] ? `0 0 ${columnWidths[3]}` : '1 1 0' }}
        >
          <span className="truncate-text">{event.eventPloy}</span>
        </div>
      </div>
    ));

    return (
      <div className="event-info-container">
        <ConfigProvider
          theme={{
            components: {
              Table: {
                cellPaddingBlock: 8,
                cellFontSize: 12,
                algorithm: true,
              },
            },
          }}
        >
          <div className="event-info-header">{headerElements}</div>
          <div
            className="event-info-body"
            ref={warperRef}
            onMouseOver={() => hoverHandler(false)}
            onMouseLeave={() => hoverHandler(true)}
          >
            <div className="content-wrapper" ref={contentWrapperRef}>
              <div className="event-info-content" ref={childDom1Ref}>
                {rowElements}
              </div>
              {scrolling && <div className="event-info-content" ref={childDom2Ref}></div>}
            </div>
          </div>
        </ConfigProvider>
      </div>
    );
  },
);

export default EventInfo;
